package zbg.sessionPage;

import zbg.cookiePage.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @program: servlet
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-03-16
 **/
@WebServlet(name = "SessionServlet",urlPatterns = "/SessionServlet")
public class SessionServlet extends BaseServlet {


    public void createSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        boolean aNew = session.isNew();
        String id = session.getId();
        resp.getWriter().write("得到的Session 他的ID是"+id+"<br/>");
        resp.getWriter().write("得到的这个Session是不是新的："+aNew+"<br/>");
    }

    public void setSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.setAttribute("userName","张三");
        resp.getWriter().write("session添加成功可以获取");
    }

    public void getSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Object userName = session.getAttribute("userName");
        if (null==userName){
            resp.getWriter().write("session是空的");
        }else {
            resp.getWriter().write("Session已经获取到"+userName);
        }
    }
    public void setSessionLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(3);
        resp.getWriter().write("设置当前session3秒失效");
    }

    public void getSessionLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        int maxInactiveInterval = session.getMaxInactiveInterval();
        resp.getWriter().write("默认的超时时长是:"+maxInactiveInterval);
    }

    public void nowDes(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.getWriter().write("设置当前session马上失效");
    }
}
